package com.leetcode.双周赛.第47场;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: xiaomi
 * @date: 2021/3/6
 * @description: 5680. 找到最近的有相同 X 或 Y 坐标的点
 * https://leetcode-cn.com/contest/biweekly-contest-47/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/
 */
public class A_5680_找到最近的有相同X或Y坐标的点 {

    public static void main(String[] args) {
        int x = 3;
        int y = 4;
        int[][] points = {{1, 2}, {3, 1}, {2, 4}, {2, 3}, {4, 4}};
        A_5680_找到最近的有相同X或Y坐标的点 acion = new A_5680_找到最近的有相同X或Y坐标的点();
        int res = acion.nearestValidPoint(x, y, points);

    }

    /**
     * 原来是返回索引最小的那个
     *
     * @param x
     * @param y
     * @param points
     * @return
     */
    public int nearestValidPoint(int x, int y, int[][] points) {
        int len = points.length;
        //记录 有效点的索引
        List<Integer> list = new ArrayList<>();
        List<Integer> distanceList = new ArrayList<>();
        int res = Integer.MAX_VALUE;
        for (int i = 0; i < len; i++) {
            if (points[i][0] == x) {
                //有效
                list.add(i);
                int disy = Math.abs(y - points[i][1]);
                distanceList.add(disy);
                res = Math.min(res, disy);
            } else if (points[i][1] == y) {
                list.add(i);
                int disx = Math.abs(x - points[i][0]);
                distanceList.add(disx);
                res = Math.min(res, Math.abs(x - points[i][0]));
            }
        }
        if (list.isEmpty()) {
            return -1;
        }
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (distanceList.get(i) == res) {
                return list.get(i);
            }
        }

        return -1;

    }
}
